package com.mesnac.comm.xml.dom4j;

import java.io.File;
import java.io.FileWriter;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.ProcessingInstruction;
import org.dom4j.VisitorSupport;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class Dom4jXmlTool {
	
	/*
	public static void main(String args[]){
		SAXReader sax = new SAXReader();
		File file = new File("");
	}
	*/
	private String filePath;
	private SAXReader sax;
	private Document doc;
	
	public Dom4jXmlTool(){
		
	}
	public Dom4jXmlTool(String filePath){
		try{
			this.filePath = filePath;
			sax = new SAXReader();
			File file = new File(filePath);
			doc = sax.read(file);
			doc.accept(new MyVisitor());
		}catch(Exception e){
			
		}
		
	}
	public class MyVisitor extends VisitorSupport{

		@Override
		public void visit(Attribute node) {
			// TODO Auto-generated method stub
			super.visit(node);
			System.out.println(node.getName()+":"+node.getValue());
		}

		@Override
		public void visit(Element node) {
			// TODO Auto-generated method stub
			super.visit(node);
			if(node.isTextOnly()){
				System.out.println(node.getName()+":"+node.getText());
			}else{
				System.out.println(node.getName());
			}
			
		}

		@Override
		public void visit(ProcessingInstruction node) {
			// TODO Auto-generated method stub
			super.visit(node);
			System.out.println(node.getTarget()+":"+node.getText());
		}
		
	}
	
	public void writeXml(String filePath){
		try{
			
			XMLWriter writer = new XMLWriter(new FileWriter(filePath));
			Document doc = createDoc();
			writer.write(doc);
			writer.close();
			
			//
			OutputFormat format = OutputFormat.createPrettyPrint();
			writer = new XMLWriter(System.out,format);
			writer.write(doc);
			writer.close();
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
	
	public Document createDoc(){
		Document doc = DocumentHelper.createDocument();
		Element root = doc.addElement("root");
		Element author1 = root.addElement("author").addAttribute("name", "Kree")
		.addAttribute("location", "UK").addText("Test");
		return doc;
		
	}

}
